package tw.com.todo.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import tw.com.todo.adapt.And001Adapter;
import tw.com.todo.adapt.And002Adapter;
import tw.com.todo.adapt.And003Adapter;

import tw.com.todo.api.And001Serivce;
import tw.com.todo.api.And002Serivce;
import tw.com.todo.api.And003Serivce;
import tw.com.todo.api.SetSerivce;
import tw.com.todo.common.AndToDoCommon;
import tw.com.todo.common.CommonCode;
import tw.com.todo.daoImp.And002DAOImp;
import tw.com.todo.db.DBConnect;

import tw.com.todo.db.dto.And001DTO;
import tw.com.todo.db.dto.And002DTO;
import tw.com.todo.db.sample.And001;
import tw.com.todo.db.sample.And002;
import tw.com.todo.db.sample.And003;
import tw.com.todo.db.sample.And004;
import tw.com.todo.db.sample.DefaultValue;
import tw.com.todo.db.sample.comm.And001DBCommon;
import tw.com.todo.db.sample.comm.And002DBCommon;
import tw.com.todo.db.sample.comm.And004DBCommon;
import tw.com.todo.dialogo.CommonDialogo;
import tw.com.todo.serivce.And001SerivceImp;
import tw.com.todo.serivce.And002SerivceImp;
import tw.com.todo.serivce.SetSerivceImp;
import android.R.color;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.renderscript.Sampler;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnDragListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AnalogClock;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DigitalClock;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class AndToDoActivity extends TabActivity implements AndToDoCommon,
		OnGestureListener, OnTouchListener, OnItemSelectedListener,
		AdapterView.OnItemLongClickListener {
	/** Called when the activity is first created. */
	private TabHost tabHost;
	// 顯示清單
	private ListView andList002;
	private ListView andList003;
	// 時間
	private DigitalClock clock;
	private Button saveBtn;
	private Button addBtn02;
	private Button addBtn03;
	private TextView saveTimeText;
	// private Button addBtn02_voice;
	// private Button addBtn03_voice;
	private EditText addText02;
	private EditText addText03;
	// 優先資料
	private TimePicker timePicker;
	private DefaultValue defaultValue;
	private static final int FLING_MIN_DISTANCE = 50;
	private static final int FLING_MIN_VELOCITY = 0;
	// 設定API
	private SetSerivce setSerivce;
	// 打卡氣
	private And001Serivce and001Serivce;
	// 工作項目應用
	private And002Serivce and002Serivce;

	// 優先值設定
	private SharedPreferences settings;

	// 資料庫連接
	private DBConnect dbConnect;
	// 輸入參數
	private And001DTO and001DTO;
	private And002DTO and002DTO;
	// 打卡顯示txt
	private TextView onWorkText;
	private TextView offWorkText;
	private TextView allTimeText;
	private TableRow goTab;
	private TableRow offTab;
	private TextView save0;
	private TextView save1;
	private TextView topic_label;
	private TextView lastTimeText;
	private TextView task_date;
	// 手勢
	private GestureDetector gestureScanner;
	//
	private PackageManager pm;
	//打卡使用
	private CheckBox isRewriteTime;

	@Override
	public void onCreate(final Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		Resources res = getResources();
		setContentView(R.layout.m1);
		// 標籤選單
		tabHost = this.getTabHost();
		setSerivce = new SetSerivceImp();
		init();
		// 取得預設值
		loadDefaultValue();
		// 資料庫連接啟動

		// 元件監聽設定
		setFindbyId();
		// tabHost.setPadding(0, -20, 0, 0);

		// // 打卡
		// saveBtn = getSaveButton();

		// TAB
		// tabHost.addTab(tabHost
		// .newTabSpec(TAB1)
		// .setIndicator(getString(R.string.check_lable),
		// res.getDrawable(R.drawable.ic_tab_artists))
		tabHost.addTab(tabHost
				.newTabSpec(TAB1)
				.setIndicator(getString(R.string.check_lable),
						res.getDrawable(R.drawable.ic_tab_artists))
				.setContent(R.id.firstText));
		tabHost.addTab(tabHost
				.newTabSpec(TAB2)
				.setIndicator(getString(R.string.today_lable),
						res.getDrawable(R.drawable.ic_tab_artists))
				.setContent(R.id.tab2));
		tabHost.addTab(tabHost
				.newTabSpec(TAB3)
				.setIndicator(getString(R.string.toDo_label),
						res.getDrawable(R.drawable.ic_tab_artists))
				.setContent(R.id.tab3));
		// 上下文選單
		// registerForContextMenu(saveBtn);

		tabHost.setOnTabChangedListener(andChageTabEvent);

		// 初始化取顯示資料
		loadListViewData();
		// ///////////////

	}

	/**
	 * 元件監聽設定
	 */
	public void setFindbyId() {

		andList002 = (ListView) findViewById(R.id.secondText);
		andList003 = (ListView) findViewById(R.id.threedText);
		addBtn02 = (Button) findViewById(R.id.addBtn02);
		addBtn03 = (Button) findViewById(R.id.addBtn03);
		addText02 = (EditText) findViewById(R.id.addText02);
		addText03 = (EditText) findViewById(R.id.addText03);
		onWorkText = (TextView) findViewById(R.id.goWokr_txt);
		offWorkText = (TextView) findViewById(R.id.offWork_txt);
		allTimeText = (TextView) findViewById(R.id.allTime_txxt);
		topic_label = (TextView) findViewById(R.id.task_topic);
		lastTimeText = (TextView) findViewById(R.id.lastTime_label);
		task_date = (TextView) findViewById(R.id.task_date);
		isRewriteTime=(CheckBox) findViewById(R.id.checktime);
		// saveTimeText = (TextView) findViewById(R.id.saveTimeSatutus);
		// addBtn02_voice = (Button) findViewById(R.id.addBtn02_voice);
		// addBtn03_voice = (Button) findViewById(R.id.addBtn03_voice);
		saveBtn = (Button) findViewById(R.id.save_btn);
		// /事件監聽
		save0 = (TextView) findViewById(R.id.onTimeT);
		save1 = (TextView) findViewById(R.id.offTimeT);
		
		timePicker=(TimePicker) findViewById(R.id.timepicker);

		// andList003.setOnItemClickListener(workClick);
		// andList002.setOnItemClickListener(workClick);

		andList003.setOnItemLongClickListener(workEvent);
		andList002.setOnItemLongClickListener(workEvent);
		// andList003.setOnTouchListener(this);
		// andList002.setOnTouchListener(this);

		// save0.setOnClickListener(onTabrowEvent);
		// save1.setOnClickListener(offTabrowEvent);
		addBtn02.setOnClickListener(addAddEvent002);
		addBtn03.setOnClickListener(addAddEvent003);
		tabHost.setOnTabChangedListener(andChageTabEvent);
		saveBtn.setOnClickListener(saveOnTimeEvent);
		saveBtn.setOnLongClickListener(timeLongClickEvent);
		saveBtn.setText(setSerivce.getDefaultValue(settings).getStatus());
		
		isRewriteTime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				showToast("123123");
				
			}
			
			
		});
	}

	/**
	 * 監聽按鍵長按事件
	 */
	public OnLongClickListener timeLongClickEvent = new OnLongClickListener() {

		public boolean onLongClick(View v) {
			AlertDialog dialog = getTimeDialogLongClick("打卡選項");
			dialog.show();
			return false;
		}
	};

	/**
	 * 清單點擊觸發事件
	 */
	public AdapterView.OnItemClickListener workClick = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			ListView list = (ListView) arg0;
			HashMap map = (HashMap) list.getItemAtPosition(arg2);

			taskDialog("工作選項", MapToAnd002DTO(map)).show();

		}
	};

	/**
	 * 清單長案觸發事件(更換)
	 */
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		ListView lView = (ListView) arg0;
		lView.getItemAtPosition(0);
		HashMap map = (HashMap) lView.getItemAtPosition(arg2);
		this.and002DTO = MapToAnd002DTO(map);
		Toast.makeText(AndToDoActivity.this, and002DTO.getName(),
				Toast.LENGTH_SHORT).show();
		return false;
	}

	/**
	 * 清單長案觸發事件
	 */
	public AdapterView.OnItemLongClickListener workEvent = new AdapterView.OnItemLongClickListener() {

		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			ListView list = (ListView) arg0;
			HashMap map = (HashMap) list.getItemAtPosition(arg2);

			taskDialog("工作選項", MapToAnd002DTO(map)).show();

			return true;

		}

	};

	/**
	 * 
	 * @param map
	 * @return
	 */
	private And002DTO MapToAnd002DTO(HashMap map) {
		And002DTO dto = new And002DTO();
		dto.setContent((String) map.get(And002DBCommon.CONTENT));
		dto.setIsFinish((String) map.get(And002DBCommon.IS_FINISH));
		dto.setIsToday((String) map.get(And002DBCommon.ISTODAY));
		dto.setN_yyymmdd((String) map.get(And002DBCommon.NYYYMMDD));
		dto.setY_yyymmdd((String) map.get(And002DBCommon.YYYYYMMDD));
		dto.setName((String) map.get(And002DBCommon.NAME));
		dto.setPriority((String) map.get(And002DBCommon.PRIORITY));
		dto.setProgress_rate((String) map.get(And002DBCommon.PROGRESS_RATE));
		dto.setUuid((String) map.get(And002DBCommon.ID));

		return dto;
	}

	/**
	 * 初始化取顯示資料
	 */
	private void loadListViewData() {
		loadSaveRecored();
		loadTodayToDo();
		loadTorrowToDo_new();
		loadTodayToDo_new();
		getlastTime();
	}

	/**
	 * 取得剩餘時間
	 */
	public void getlastTime() {
		String hour = setSerivce.getDefaultValue(settings).getHour();

		lastTimeText.setText(getString(R.string.tipLabel) + hour + "時");

	}

	/**
	 * 打卡對話框
	 */
	public OnClickListener saveOnTimeEvent = new OnClickListener() {

		public void onClick(View v) {
			// TODO
			 AlertDialog dialog=getTimeDialog("");
			 dialog.show();
//			CommonDialogo commonDialogo = new CommonDialogo("打卡",
//					AndToDoActivity.this, R.layout.dialogtime, "打卡時間，並點擊確定",
//					defaultValue);
//			commonDialogo.setDto(and001DTO);
//			commonDialogo.show();
//			showToast(String.format("時間[h=%s,m=%s]", commonDialogo.getHour(),
//					commonDialogo.getMinute()));
		}

	};

	/**
	 * 新增工作詳細選單
	 * 
	 * @param title
	 * @param dto
	 * @return
	 */
	public AlertDialog taskDialog(String title, And002DTO dto) {
		// 產生一個Builder物件
		Builder builder = new AlertDialog.Builder(AndToDoActivity.this);
		// 設定Dialog的標題
		builder.setTitle(title);
		// and002DTO.setUuid(dto.getUuid());
		and002DTO = dto;
		CharSequence[] list = { "編輯", "刪除", "完成", "轉移" };
		builder.setNegativeButton(getString(R.string.cancel_lable), null);
		builder.setItems(list, taskEvent);
		// 利用Builder物件建立AlertDialog
		return builder.create();

	}


	public AlertDialog getDefaultClick(String title) {
		// 產生一個Builder物件
		Builder builder = new AlertDialog.Builder(AndToDoActivity.this);
		LayoutInflater inflater;
		inflater = LayoutInflater.from(this);
		// 設定Dialog的標題
		builder.setTitle(title);
		builder.setView(inflater.inflate(R.layout.dialogtime, null));
		// and002DTO.setUuid(dto.getUuid());
		
		if (defaultValue.isOnCheck()) {

		} else {

		}
		builder.setNegativeButton(getString(R.string.cancel_lable), null);
		// builder.setItems(chechList, taskEvent);
		// 利用Builder物件建立AlertDialog
		return builder.create();

	}


	public AlertDialog getTimeDialogLongClick(String title) {
		// 產生一個Builder物件
		Builder builder = new AlertDialog.Builder(AndToDoActivity.this);
		// 設定Dialog的標題
	//	builder.setTitle(title);
		LayoutInflater inflater;
		inflater = LayoutInflater.from(this);
		builder.setView(inflater.inflate(R.layout.dialogtime, null));
		// and002DTO.setUuid(dto.getUuid());
//
//		final CharSequence[] onList = { "上班", "更新", "取消", };
//		final CharSequence[] offList = { "下班", "更新", "儲存", };
		CharSequence[] chechList = null;
		if (defaultValue.isOnCheck()) {
			builder.setTitle("下班打卡");
			defaultValue.setOnCheck(false
					);
			
			//chechList = offList;
		} else {			
			builder.setTitle("上班打卡");
			defaultValue.setOnCheck(true);
			//chechList = onList;
		}		
		builder.setNegativeButton(getString(R.string.cancel_lable), null);
		builder.setPositiveButton(getString(R.string.check_lable), null);
		builder.setItems(chechList, taskEvent);
		// 利用Builder物件建立AlertDialog
		return builder.create();

	}

	public DialogInterface.OnClickListener taskEvent = new DialogInterface.OnClickListener() {

		public void onClick(DialogInterface dialog, int which) {
			try {
				checkTask(which);
			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}

	};

	/**
	 * 0:編輯 1:刪除 2.完成 3.轉移
	 * 
	 * @param kind
	 */
	public void checkTask(int kind) {
		SQLiteDatabase data = dbConnect.getWritableDatabase();
		switch (kind) {

		case 0:

			Intent i1 = new Intent(AndToDoActivity.this, Detial.class);

			i1.putExtra("pk", this.and002DTO.getUuid());

			startActivityForResult(i1, SEND_TASK_UPDATA);

			break;
		case 1:
			and002Serivce.deleteTask(data, this.and002DTO);
			Toast.makeText(this, "刪除成功", Toast.LENGTH_SHORT).show();

			break;

		case 2:
			Toast.makeText(this, "完成", Toast.LENGTH_SHORT).show();

			and002Serivce.finishTask(data, this.and002DTO);
			break;

		case 3:
			Toast.makeText(this, "轉移", Toast.LENGTH_SHORT).show();
			break;

		default:

			break;
		}
		loadListViewData();
	}

	/**
	 * 取得打卡對話框
	 * 
	 * @param title
	 * @param message
	 * @return
	 */
	
	//TODO
	private AlertDialog getTimeDialog(String message) {
		// 產生一個Builder物件
		final Builder builder = new AlertDialog.Builder(AndToDoActivity.this);
		final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
		final SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss ");

		final Date date = new Date();

		// 設定Dialog的標題
		builder.setTitle(timeFormat.format(date));
		// 設定Dialog的內容
	
		LayoutInflater inflater;
		inflater = LayoutInflater.from(this);
		builder.setView(inflater.inflate(R.layout.dialogtime, null));
		
		
	//	timePicker
		// ArrayAdapter<
		// CharSequence>array=ArrayAdapter.createFromResource(this,
		// R.array.Houres, android.R.layout.simple_list_item_checked);

		// 設定Positive按鈕資料
		
		builder.setNeutralButton("修改",null);
		builder.setPositiveButton(getString(R.string.ok_label),
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface arg0, int arg1) {
						if (!defaultValue.isOnCheck()) {
							
							ContentValues map = new ContentValues();
							Date date = new Date();
							SQLiteDatabase timeDatabase = dbConnect
									.getWritableDatabase();
							and001DTO.setStatus("1");
							and001DTO.setNo(UUID.randomUUID().toString());
							and001DTO.setOnWorkTime(timeFormat.format(date));
							and001DTO.setOnWorkDate(dateFormat.format(date));
							map = And001DTOToMap(and001DTO);
							try {
								and001Serivce.create(timeDatabase, and001DTO);
								showToast(getString(R.string.workMessage));
								// /打卡成功後，儲存資訊
								defaultValue.setTaskId(and001DTO.getNo());
								defaultValue.setStatus(and001DTO.getStatus());
								defaultValue.setOnCheck(true);
								defaultValue
										.setStatus(getString(R.string.onWorking));
								setSerivce.save(settings, defaultValue);
							} catch (Exception e) {
								e.printStackTrace();
							} finally {
								saveBtn.setText(setSerivce.getDefaultValue(
										settings).getStatus());
								saveBtn.setBackgroundColor(Color.RED);
								loadSaveRecored();
							}
						} else {
							ContentValues map = new ContentValues();
						
							Date date = new Date();
							SQLiteDatabase timeDatabase = dbConnect
									.getWritableDatabase();
							timeDatabase = dbConnect.getWritableDatabase();

							and001DTO.setOffWorkDate(dateFormat.format(date));
							and001DTO.setOffWorkTime(timeFormat.format(date));

							try {
								and001Serivce.upData(timeDatabase, and001DTO);
								defaultValue.setOnCheck(false);
								defaultValue
										.setStatus(getString(R.string.beOff));
								setSerivce.save(settings, defaultValue);
							} catch (Exception e) {

								e.printStackTrace();
							}

							saveBtn.setText(setSerivce
									.getDefaultValue(settings).getStatus());
							saveBtn.setBackgroundColor(Color.GREEN);
						}

					}

				});
		// 設定Negative按鈕資料
		builder.setNegativeButton(getString(R.string.cancel_lable),
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

					}

				});
		// 利用Builder物件建立AlertDialog
		return builder.create();
	}

	/**
	 * 警告對話框控制器
	 * 
	 * @param title
	 * @param message
	 * @return
	 */
	private AlertDialog getAlertDialog(String title, String message) {
		// 產生一個Builder物件
		Builder builder = new AlertDialog.Builder(AndToDoActivity.this);
		// 設定Dialog的標題
		builder.setTitle(title);
		// 設定Dialog的內容
		builder.setMessage(message);
		// ArrayAdapter<
		// CharSequence>array=ArrayAdapter.createFromResource(this,
		// R.array.Houres, android.R.layout.simple_list_item_checked);

		// 設定Positive按鈕資料
		builder.setPositiveButton(getString(R.string.ok_label),
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface arg0, int arg1) {
						if (!isFinishing()) {
							AndToDoActivity.this.finish();
						}
					}

				});
		// 設定Negative按鈕資料
		builder.setNegativeButton(getString(R.string.cancel_lable),
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

					}

				});
		// 利用Builder物件建立AlertDialog
		return builder.create();
	}

	/**
	 * 參數初始化
	 */
	public void init() {

		defaultValue = new DefaultValue();
		// /Service
		and002Serivce = new And002SerivceImp();
		and001Serivce = new And001SerivceImp();
		setSerivce = new SetSerivceImp();
		settings = getSharedPreferences(DEFAULT_VALUE_PATH, 0);
		and002DTO = new And002DTO();

		gestureScanner = new GestureDetector(this);
		and001DTO = new And001DTO();
		// pm = getPackageManager();
		// List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
		// RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		// if (activities.size() != 0) {
		// addBtn02_voice.setEnabled(false);
		// addBtn03_voice.setEnabled(false);
		// }
		dbConnect = new DBConnect(this);
	}

	public void speakButtonClicked(View v) {
		startVoiceRecognitionActivity();
	}

	private void startVoiceRecognitionActivity() {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "語音輸入工作項目");
		startActivityForResult(intent, SEND_SPEEED);
	}

	/**
	 * 選項
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_ABOUT, 0, getString(R.string.about_lable));
		menu.add(0, MENU_SET, 0, getString(R.string.set_lable));
		return true;

	}

	/**
	 * Menu選單事件
	 * 
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent thisIntent;
		switch (item.getItemId()) {
		case MENU_ABOUT:
			thisIntent = new Intent();
			thisIntent.setClass(AndToDoActivity.this, AboutActivity.class);
			startActivity(thisIntent);
			break;
		case MENU_SET:
			thisIntent = new Intent();
			thisIntent.setClass(AndToDoActivity.this, SetAcitvity.class);
			startActivity(thisIntent);
			break;

		default:
			break;
		}

		return false;
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final Date date = new Date();
		// final TextView text=(TextView)findViewById(R.id.timeText1);

		final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		final SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss a");

		ContentValues map = new ContentValues();
		showToast(String.valueOf(defaultValue.isOnCheck()));
		switch (item.getItemId()) {
	
		case CHECK_1:

			SQLiteDatabase timeDatabase = dbConnect.getWritableDatabase();
			and001DTO.setStatus("1");
			and001DTO.setNo(UUID.randomUUID().toString());
			and001DTO.setOnWorkTime(timeFormat.format(date));
			and001DTO.setOnWorkDate(dateFormat.format(date));
			map = And001DTOToMap(and001DTO);
			try {
				and001Serivce.create(timeDatabase, and001DTO);
				showToast(getString(R.string.workMessage));
				// /打卡成功後，儲存資訊
				defaultValue.setTaskId(and001DTO.getNo());
				defaultValue.setStatus(and001DTO.getStatus());
				defaultValue.setOnCheck(true);
				defaultValue.setStatus(getString(R.string.onWorking));
				setSerivce.save(settings, defaultValue);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				saveBtn.setText(setSerivce.getDefaultValue(settings)
						.getStatus());
				saveBtn.setBackgroundColor(Color.RED);
			}

			break;
		case CHECK_2:
			timeDatabase = dbConnect.getWritableDatabase();

			and001DTO.setOffWorkDate(dateFormat.format(date));
			and001DTO.setOffWorkTime(timeFormat.format(date));

			try {
				and001Serivce.upData(timeDatabase, and001DTO);
				defaultValue.setOnCheck(false);
				defaultValue.setStatus(getString(R.string.beOff));
				setSerivce.save(settings, defaultValue);
			} catch (Exception e) {

				e.printStackTrace();
			}

			saveBtn.setText(setSerivce.getDefaultValue(settings).getStatus());
			saveBtn.setBackgroundColor(Color.GREEN);

			break;
		case CANCER_CHECK:
			timeDatabase = dbConnect.getWritableDatabase();

			try {
				and001Serivce.delete(timeDatabase, and001DTO);
				setSerivce.initValue(settings);
				saveBtn.setText(setSerivce.getDefaultValue(settings)
						.getStatus());
				saveBtn.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.comm_btn));

			} catch (Exception e) {

				e.printStackTrace();
			}
			break;
		case SAVE_CHECK:
			setSerivce.initValue(settings);
			saveBtn.setText(setSerivce.getDefaultValue(settings).getStatus());
			saveBtn.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.comm_btn));
			break;
		}
		loadDefaultValue();
		loadSaveRecored();
		return true;

	}

	private void buttonBackground() {
		if (defaultValue.isOnCheck()) {

		}
	}

	/**
	 * And001DTOToMap
	 * 
	 * @return
	 */
	@SuppressWarnings("unused")
	private ContentValues And001DTOToMap(And001DTO dto) {
		ContentValues map = new ContentValues();
		map.put(And001DBCommon.STATUS, dto.getStatus());
		map.put(And001DBCommon.GO_SAVE_DATE, dto.getOnWorkDate());
		map.put(And001DBCommon.GO_SAVE_TIME, dto.getOnWorkTime());
		map.put(And001DBCommon.OFF_SAVE_DATE, dto.getOffWorkDate());
		map.put(And001DBCommon.OFF_SAVE_TIME, dto.getOffWorkTime());
		return map;
	}

	/**
	 * 
	 * 打卡
	 * 
	 * @return
	 */
	public Button getSaveButton() {
		Button btn = (Button) findViewById(R.id.save_btn);
		// final Date date = new Date();
		// final TextView text=(TextView)findViewById(R.id.timeText1);

		// final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
		// final SimpleDateFormat timeFormat = new
		// SimpleDateFormat("hh:mm:ss a");
		//
		// //
		// btn.setOnClickListener(new OnClickListener() {
		//
		// public void onClick(View v) {
		//
		// ContentValues map = new ContentValues();
		// map.put(And001DBCommon.STATUS, "1");
		// map.put(And001DBCommon.SAVE_DATE, dateFormat.format(date));
		// map.put(And001DBCommon.SAVE_TIME, timeFormat.format(date));
		//
		// try {
		// SQLiteDatabase timeDatabase = dbConnect
		// .getWritableDatabase();
		//
		// timeDatabase.insert(And001DBCommon.DB_TABLE, null, map);
		//
		// Toast.makeText(AndToDoActivity.this, "打卡成功",
		// Toast.LENGTH_SHORT).show();
		// } catch (Exception ex) {
		// Toast.makeText(AndToDoActivity.this, "打卡失敗",
		// Toast.LENGTH_SHORT).show();
		//
		// ex.printStackTrace();
		// } finally {
		//
		// }
		//
		// }
		// });

		return btn;

	}

	@Override
	public void onCreateContextMenu(ContextMenu contextMenu, View view,
			ContextMenuInfo menuInfo) {
		// 設定選單內容
		super.onCreateContextMenu(contextMenu, view, menuInfo);
		if (defaultValue.isOnCheck()) {

			contextMenu.add(0, AndToDoCommon.CHECK_2, 0, "下班");
			contextMenu.add(0, AndToDoCommon.CANCER_CHECK, 0, "清除");

		} else {
			contextMenu.add(0, AndToDoCommon.CHECK_1, 0, "上班");
			contextMenu.add(0, AndToDoCommon.CANCER_CHECK, 0, "清除");
			contextMenu.add(0, AndToDoCommon.SAVE_CHECK, 0, "儲存");
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		// Toast.makeText(this, "Destory CLOSE",Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onStop() {
		super.onStop();

		// Toast.makeText(this, "Stop CLOSE",Toast.LENGTH_SHORT).show();
	}

	/**
	 * 存檔按鈕控制器02
	 */
	OnClickListener addAddEvent002 = new OnClickListener() {
		public void onClick(View v) {
			Toast.makeText(AndToDoActivity.this, "SaveToday",
					Toast.LENGTH_SHORT).show();
			insertTask();

		}

	};
	/**
	 * 存檔按鈕控制器03
	 */
	OnClickListener addAddEvent003 = new OnClickListener() {
		public void onClick(View v) {
			Toast.makeText(AndToDoActivity.this, "SaveTorrow",
					Toast.LENGTH_SHORT).show();
			insertTaskTorrow();
		}

	};

	/**
	 * 取得優先參數
	 */
	public void loadDefaultValue() {
		defaultValue = setSerivce.getDefaultValue(settings);
	}

	/**
	 * 取得剩下時間
	 */
	public void getLastHour() {

	}

	/**
	 * 取得頁面資料
	 */
	public void getCheckData() {

	}

	/**
	 * 新增今日工作項目
	 */
	public void insertTask() {
		SQLiteDatabase timeDatabase = dbConnect.getWritableDatabase();

		and002DTO.setName(addText02.getText().toString());
		and002DTO.setContent("");
		and002DTO.setIsFinish("0");
		and002DTO.setN_yyymmdd(" ");
		and002DTO.setY_yyymmdd(" ");
		and002DTO.setProgress_rate("0");
		and002DTO.setIsFinish("0");
		and002DTO.setIsToday("1");

		/**
		 * 設定預設優先權
		 */
		and002DTO.setPriority(setSerivce.getDefaultValue(settings)
				.getPriority());

		if (!and002DTO.getName().trim().equals("")) {
			try {
				and002Serivce.addImmTaskToday(timeDatabase, and002DTO);
				Toast.makeText(this, getString(R.string.addToDoMesY),
						Toast.LENGTH_SHORT).show();

			} catch (Exception e) {
				Toast.makeText(this, getString(R.string.addToDoMesY),
						Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}

		} else {
			Toast.makeText(this, getString(R.string.addToDoMesUn),
					Toast.LENGTH_SHORT).show();
		}
		addText02.setText("");
		loadTodayToDo_new();
	}

	/**
	 * 新增未來工作項目
	 */
	public void insertTaskTorrow() {
		SQLiteDatabase timeDatabase = dbConnect.getWritableDatabase();

		and002DTO.setName(addText03.getText().toString());
		and002DTO.setContent("");
		and002DTO.setIsFinish("0");
		and002DTO.setN_yyymmdd(" ");
		and002DTO.setY_yyymmdd(" ");
		and002DTO.setProgress_rate("0");
		and002DTO.setIsFinish("0");
		and002DTO.setIsToday("0");
		/**
		 * 設定預設優先權
		 */
		and002DTO.setPriority(setSerivce.getDefaultValue(settings)
				.getPriority());

		if (!and002DTO.getName().trim().equals("")) {
			try {
				and002Serivce.addImmTaskTorrow(timeDatabase, and002DTO);
				Toast.makeText(this, getString(R.string.addToDoMesY),
						Toast.LENGTH_SHORT).show();

			} catch (Exception e) {
				Toast.makeText(this, getString(R.string.addToDoMesY),
						Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}

		} else {
			Toast.makeText(this, getString(R.string.addToDoMesUn),
					Toast.LENGTH_SHORT).show();
		}
		addText03.setText("");
		loadTorrowToDo_new();
	}

	/**
	 * 讀取全部工作
	 */
	public void loadTodayToDo() {
		SQLiteDatabase timeDatabase = dbConnect.getWritableDatabase();
		HashMap<String, Object> timeMap = new HashMap<String, Object>();
		List<HashMap<String, Object>> timeSave = new ArrayList<HashMap<String, Object>>();
		Cursor c = and002Serivce.getTaskAllToday(timeDatabase);

		c.moveToFirst();
		for (int i = 0; i < c.getCount(); i++) {
			timeMap = new HashMap<String, Object>();
			timeMap.put(And002DBCommon.ID,
					c.getString(c.getColumnIndex(And002DBCommon.ID)));
			timeMap.put(And002DBCommon.NAME,
					c.getString(c.getColumnIndex(And002DBCommon.NAME)));
			timeMap.put(And002DBCommon.CONTENT,
					c.getString(c.getColumnIndex(And002DBCommon.CONTENT)));
			timeSave.add(timeMap);
			c.moveToNext();
		}
		And002Adapter saveAdapter = new And002Adapter(this, timeSave,
				R.layout.tasklayout).getAnd002Adapter();

		andList002.setAdapter(saveAdapter);

	}

	/**
	 * 讀取TODAY工作
	 */
	public void loadTodayToDo_new() {
		SQLiteDatabase timeDatabase = dbConnect.getWritableDatabase();
		HashMap<String, Object> timeMap = new HashMap<String, Object>();
		List<HashMap<String, Object>> timeSave = new ArrayList<HashMap<String, Object>>();
		Cursor c = and002Serivce.getTasOnToday(timeDatabase);
		try {
			c.moveToFirst();
			for (int i = 0; i < c.getCount(); i++) {
				timeMap = new HashMap<String, Object>();
				timeMap.put(And002DBCommon.ID,
						c.getString(c.getColumnIndex(And002DBCommon.ID)));
				timeMap.put(And002DBCommon.NAME,
						c.getString(c.getColumnIndex(And002DBCommon.NAME)));
				timeMap.put(And002DBCommon.CONTENT,
						c.getString(c.getColumnIndex(And002DBCommon.CONTENT)));
				timeMap.put(And002DBCommon.NYYYMMDD,
						c.getString(c.getColumnIndex(And002DBCommon.NYYYMMDD)));
				timeMap.put(And002DBCommon.PROGRESS_RATE, c.getString(c
						.getColumnIndex(And002DBCommon.PROGRESS_RATE)));
				timeSave.add(timeMap);
				// Toast.makeText(
				// this,
				// c.getString(c.getColumnIndex(And002DBCommon.IS_FINISH)),
				// Toast.LENGTH_SHORT).show();
				c.moveToNext();
			}
			And002Adapter saveAdapter = new And002Adapter(this, timeSave,
					R.layout.tasklayout).getAnd002Adapter();
			andList002.setAdapter(saveAdapter);
		} catch (Exception ex) {

		}

	}

	/**
	 * 讀取未來工作
	 */
	public void loadTorrowToDo_new() {
		SQLiteDatabase timeDatabase = dbConnect.getWritableDatabase();
		HashMap<String, Object> timeMap = new HashMap<String, Object>();
		List<HashMap<String, Object>> timeSave = new ArrayList<HashMap<String, Object>>();
		Cursor c = and002Serivce.getTaskOnTorrow(timeDatabase);
		try {
			c.moveToFirst();
			for (int i = 0; i < c.getCount(); i++) {
				timeMap = new HashMap<String, Object>();
				timeMap.put(And002DBCommon.ID,
						c.getString(c.getColumnIndex(And002DBCommon.ID)));
				timeMap.put(And002DBCommon.NAME,
						c.getString(c.getColumnIndex(And002DBCommon.NAME)));
				timeMap.put(And002DBCommon.CONTENT,
						c.getString(c.getColumnIndex(And002DBCommon.CONTENT)));
				timeMap.put(And002DBCommon.NYYYMMDD,
						c.getString(c.getColumnIndex(And002DBCommon.NYYYMMDD)));
				timeMap.put(And002DBCommon.PROGRESS_RATE, c.getString(c
						.getColumnIndex(And002DBCommon.PROGRESS_RATE)));
				timeSave.add(timeMap);
				// Toast.makeText(
				// AndToDoActivity.this,
				// c.getString(c
				// .getColumnIndex(And002DBCommon.PROGRESS_RATE)),
				// Toast.LENGTH_SHORT).show();
				c.moveToNext();
			}
			And002Adapter saveAdapter = new And002Adapter(this, timeSave,
					R.layout.tasklayout).getAnd002Adapter();

			andList003.setAdapter(saveAdapter);

		} catch (Exception ex) {
		}

	}

	/**
	 * 取出打卡紀錄
	 */
	public void loadSaveRecored() {
		SQLiteDatabase timeDatabase = dbConnect.getWritableDatabase();
		final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
		final SimpleDateFormat OSDF = new SimpleDateFormat("hh:mm:ss ");
		Date off;
		Date go;
		Log.d(TAG_MAIN, "loadSaveRecored");
		and001DTO.setNo(setSerivce.getDefaultValue(settings).getTaskId());
		try {
			// timeCSave = and001Serivce.getOnCheck(timeDatabase, null);
			// timeCSave.moveToLast();
			// setSerivce.getDefaultValue(settings).getTaskId();

			// 取得上下班時間
			and001DTO = and001Serivce.getOnAndOffTime(timeDatabase, and001DTO);

			// onWorkText.setText(timeCSave.getString(4));
			// go = sdf.parse(timeCSave.getString(4));
			// timeCSave = and001Serivce.getOffCheck(timeDatabase, null);
			// timeCSave.moveToLast();
			// offWorkText.setText(timeCSave.getString(4));
			// off = sdf.parse(timeCSave.getString(4));
			onWorkText.setText(and001DTO.getOnWorkTime());
			offWorkText.setText(and001DTO.getOffWorkTime());
			// And001Adapter timeAdapter = new And001Adapter(this, timeSave,
			// R.layout.time).getTimeAdapter();

			// timeListView.setAdapter(timeAdapter);
			// Date time = null;
			// time = new Date(off.getTime() - go.getTime());
			// Long alltime = (off.getTime() - go.getTime()) / 1000;
			// int hour = 0;
			// int min = (int) (alltime % 60);
			// hour = (int) (min / (60));
			// if (alltime < 0) {
			// allTimeText.setText("");
			// } else {
			// allTimeText.setText(hour + "小時" + min + "分");
			// }

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {

		}
	}

	/**
	 * 切換tab事件
	 */
	public OnTabChangeListener andChageTabEvent = new OnTabChangeListener() {

		public void onTabChanged(String tabId) {
			if (tabId == CommonCode.tab1.name()) {

				loadSaveRecored();
			} else if (tabId == CommonCode.tab2.name()) {
				loadTodayToDo_new();
			} else if (tabId == CommonCode.tab3.name()) {
				loadTorrowToDo_new();
			}
			cleanEditViewText();
		}

	};

	public void cleanEditViewText() {
		addText02.setText("");
		addText03.setText("");
	}

	/**
	 * tab2之checkbox 之控制器
	 */
	public CompoundButton.OnCheckedChangeListener isDoneCheckBoxEvent = new CompoundButton.OnCheckedChangeListener() {

		public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
			// Toast.makeText(AndToDoActivity.this,"OnCheckedChangeListener1",
			// Toast.LENGTH_SHORT).show();

		}

	};
	/**
	 * tab3之checkbox 之控制器
	 */
	public CompoundButton.OnCheckedChangeListener isDoneCheckBoxEvent1 = new CompoundButton.OnCheckedChangeListener() {
		public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
			// Toast.makeText(AndToDoActivity.this,"OnCheckedChangeListener2",
			// Toast.LENGTH_SHORT).show();

		}

	};

	// /**
	// * 上班tabrow 監聽
	// */
	// public OnClickListener onTabrowEvent = new OnClickListener() {
	// ContentValues map = new ContentValues();
	// final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
	// final SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss a");
	// final Date date = new Date();
	//
	// public void onClick(View v) {
	// SQLiteDatabase timeDatabase = dbConnect.getWritableDatabase();
	// timeDatabase = dbConnect.getWritableDatabase();
	// map.put(And001DBCommon.STATUS, "1");
	// map.put(And001DBCommon.SAVE_DATE, dateFormat.format(date));
	// map.put(And001DBCommon.SAVE_TIME, timeFormat.format(date));
	// Toast.makeText(AndToDoActivity.this,
	// getString(R.string.workMessage), Toast.LENGTH_SHORT).show();
	// timeDatabase.insert(And001DBCommon.DB_TABLE, null, map);
	// loadSaveRecored();
	// }
	// };
	/**
	 * 下班tabrow 監聽
	 */
	// public OnClickListener offTabrowEvent = new OnClickListener() {
	// ContentValues map = new ContentValues();
	// final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
	// final SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss a");
	// final Date date = new Date();
	//
	// public void onClick(View v) {
	// SQLiteDatabase timeDatabase = dbConnect.getWritableDatabase();
	// timeDatabase = dbConnect.getWritableDatabase();
	// map.put(And001DBCommon.STATUS, "1");
	// map.put(And001DBCommon.SAVE_DATE, dateFormat.format(date));
	// map.put(And001DBCommon.SAVE_TIME, timeFormat.format(date));
	// Toast.makeText(AndToDoActivity.this,
	// getString(R.string.unWorkMessage), Toast.LENGTH_SHORT)
	// .show();
	// timeDatabase.insert(And001DBCommon.DB_TABLE, null, map);
	// loadSaveRecored();
	// }
	// };

	// /**
	// *
	// */
	// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long
	// arg3) {
	// ListView lView = (ListView) arg0;
	// lView.getItemAtPosition(0);
	// HashMap map = (HashMap) lView.getItemAtPosition(arg2);
	// this.and002DTO= MapToAnd002DTO(map);
	// Toast.makeText(AndToDoActivity.this,
	// and002DTO.getName(),Toast.LENGTH_SHORT ).show();
	//
	// }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			AlertDialog dialog = getAlertDialog(null, "是否要關閉");
			dialog.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// Main等待回應信息
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Toast.makeText(this, requestCode+"/"+resultCode,
		// Toast.LENGTH_SHORT).show();
		ArrayList<String> matches = new ArrayList<String>(0);
		if (resultCode == RESULT_OK) {

			switch (requestCode) {
			case SEND_TASK_UPDATA:
				loadListViewData();
				break;

			case SEND_SPEEED:

				matches = data
						.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
				addText02.setText(matches.get(0));
				addText03.setText(matches.get(0));
				break;

			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	public boolean onDown(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		SQLiteDatabase data = dbConnect.getWritableDatabase();
		// Toast.makeText(this, "onFling", Toast.LENGTH_SHORT).show();
		if (and002DTO.getName() != null) {
			if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
					&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
				and002DTO.setIsToday("1");
				and002Serivce.updataTask(data, this.and002DTO);

				Toast.makeText(this, "left", Toast.LENGTH_SHORT).show();
				return true;
			} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
					&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
				and002DTO.setIsToday("0");

				and002Serivce.updataTask(data, this.and002DTO);

				Toast.makeText(this, "right", Toast.LENGTH_SHORT).show();
				return true;
			}
		}

		loadListViewData();
		return false;
	}

	public void onLongPress(MotionEvent arg0) {
		// TODO Auto-generated method stub

	}

	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onShowPress(MotionEvent arg0) {
		// TODO Auto-generated method stub

	}

	public boolean onSingleTapUp(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean onTouch(View arg0, MotionEvent arg1) {

		return gestureScanner.onTouchEvent(arg1);
	}

	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		ListView lView = (ListView) arg0;
		lView.getItemAtPosition(0);
		HashMap map = (HashMap) lView.getItemAtPosition(arg2);
		this.and002DTO = MapToAnd002DTO(map);
		// Toast.makeText(AndToDoActivity.this, and002DTO.getName(),
		// Toast.LENGTH_SHORT).show();

	}

	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	/**
	 * 顯示TOAST的方法
	 * 
	 * @param abc
	 */
	private void showToast(String content) {
		Toast.makeText(AndToDoActivity.this, content, Toast.LENGTH_LONG).show();
	}

}